const express = require('express');
const router = express.Router();
const schedulerService = require('../services/schedulerService');
const { validateRequest } = require('../middleware/validation');
const logger = require('../utils/logger');

/**
 * @route GET /api/scheduler/status
 * @desc 获取调度器状态
 * @access Private
 */
router.get('/status', async (req, res) => {
  try {
    logger.info('获取调度器状态');
    
    const status = schedulerService.getSchedulerStatus();
    
    res.json({
      success: true,
      data: status,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取调度器状态失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取调度器状态失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route GET /api/scheduler/tasks
 * @desc 获取所有定时任务状态
 * @access Private
 */
router.get('/tasks', async (req, res) => {
  try {
    logger.info('获取所有定时任务状态');
    
    const tasks = schedulerService.getTaskStatus();
    
    res.json({
      success: true,
      data: tasks,
      count: tasks.length,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error('获取定时任务状态失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取定时任务状态失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route GET /api/scheduler/tasks/:taskName
 * @desc 获取指定定时任务状态
 * @access Private
 */
router.get('/tasks/:taskName', async (req, res) => {
  try {
    const { taskName } = req.params;
    
    logger.info(`获取定时任务状态: ${taskName}`);
    
    const task = schedulerService.getTaskStatus(taskName);
    
    if (!task) {
      return res.status(404).json({
        success: false,
        error: '定时任务不存在',
        message: `找不到名为 ${taskName} 的定时任务`,
        timestamp: new Date().toISOString()
      });
    }
    
    res.json({
      success: true,
      data: task,
      timestamp: new Date().toISOString()
    });
  } catch (error) {
    logger.error(`获取定时任务状态失败: ${req.params.taskName}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '获取定时任务状态失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/tasks
 * @desc 添加新的定时任务
 * @access Private
 */
router.post('/tasks', validateRequest({
  name: 'string|required',
  schedule: 'string|required',
  description: 'string|optional',
  timezone: 'string|optional'
}), async (req, res) => {
  try {
    const { name, schedule, description, timezone } = req.body;
    
    logger.info(`添加新的定时任务: ${name}`, { schedule, timezone });
    
    // 这里可以添加自定义任务逻辑
    // 目前只支持预定义的任务类型
    const supportedTasks = [
      'dataSync', 'cacheRefresh', 'healthCheck', 'marketDataUpdate',
      'systemMaintenance', 'logCleanup', 'dataBackup'
    ];
    
    if (!supportedTasks.includes(name)) {
      return res.status(400).json({
        success: false,
        error: '不支持的任务类型',
        message: `目前只支持以下任务类型: ${supportedTasks.join(', ')}`,
        supportedTasks,
        timestamp: new Date().toISOString()
      });
    }
    
    // 创建自定义任务函数
    const customTask = async () => {
      try {
        logger.info(`执行自定义定时任务: ${name}`, { description });
        // 这里可以根据任务名称执行相应的逻辑
        await schedulerService.executeTaskNow(name);
        logger.info(`自定义定时任务 ${name} 执行完成`);
      } catch (error) {
        logger.error(`自定义定时任务 ${name} 执行失败`, { error: error.message });
        throw error;
      }
    };
    
    const success = schedulerService.addTask(name, schedule, customTask, {
      timezone: timezone || 'Asia/Shanghai',
      description
    });
    
    if (success) {
      res.json({
        success: true,
        message: `定时任务 ${name} 添加成功`,
        data: {
          name,
          schedule,
          timezone: timezone || 'Asia/Shanghai',
          description
        },
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(500).json({
        success: false,
        error: '添加定时任务失败',
        message: '请检查cron表达式是否正确',
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error('添加定时任务失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '添加定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route DELETE /api/scheduler/tasks/:taskName
 * @desc 删除定时任务
 * @access Private
 */
router.delete('/tasks/:taskName', async (req, res) => {
  try {
    const { taskName } = req.params;
    
    logger.info(`删除定时任务: ${taskName}`);
    
    const success = schedulerService.removeTask(taskName);
    
    if (success) {
      res.json({
        success: true,
        message: `定时任务 ${taskName} 删除成功`,
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(404).json({
        success: false,
        error: '删除定时任务失败',
        message: `找不到名为 ${taskName} 的定时任务`,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error(`删除定时任务失败: ${req.params.taskName}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '删除定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/tasks/:taskName/start
 * @desc 启动指定定时任务
 * @access Private
 */
router.post('/tasks/:taskName/start', async (req, res) => {
  try {
    const { taskName } = req.params;
    
    logger.info(`启动定时任务: ${taskName}`);
    
    const success = schedulerService.startTask(taskName);
    
    if (success) {
      res.json({
        success: true,
        message: `定时任务 ${taskName} 启动成功`,
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(400).json({
        success: false,
        error: '启动定时任务失败',
        message: `无法启动定时任务 ${taskName}`,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error(`启动定时任务失败: ${req.params.taskName}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '启动定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/tasks/:taskName/stop
 * @desc 停止指定定时任务
 * @access Private
 */
router.post('/tasks/:taskName/stop', async (req, res) => {
  try {
    const { taskName } = req.params;
    
    logger.info(`停止定时任务: ${taskName}`);
    
    const success = schedulerService.stopTask(taskName);
    
    if (success) {
      res.json({
        success: true,
        message: `定时任务 ${taskName} 停止成功`,
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(400).json({
        success: false,
        error: '停止定时任务失败',
        message: `无法停止定时任务 ${taskName}`,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error(`停止定时任务失败: ${req.params.taskName}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '停止定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/tasks/:taskName/execute
 * @desc 立即执行指定定时任务
 * @access Private
 */
router.post('/tasks/:taskName/execute', async (req, res) => {
  try {
    const { taskName } = req.params;
    
    logger.info(`立即执行定时任务: ${taskName}`);
    
    const success = await schedulerService.executeTaskNow(taskName);
    
    if (success) {
      res.json({
        success: true,
        message: `定时任务 ${taskName} 执行成功`,
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(400).json({
        success: false,
        error: '执行定时任务失败',
        message: `无法执行定时任务 ${taskName}`,
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error(`执行定时任务失败: ${req.params.taskName}`, { error: error.message });
    res.status(500).json({
      success: false,
      error: '执行定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/start
 * @desc 启动所有定时任务
 * @access Private
 */
router.post('/start', async (req, res) => {
  try {
    logger.info('启动所有定时任务');
    
    const success = schedulerService.startTask();
    
    if (success) {
      res.json({
        success: true,
        message: '所有定时任务启动成功',
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(500).json({
        success: false,
        error: '启动定时任务失败',
        message: '部分或全部定时任务启动失败',
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error('启动所有定时任务失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '启动定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/stop
 * @desc 停止所有定时任务
 * @access Private
 */
router.post('/stop', async (req, res) => {
  try {
    logger.info('停止所有定时任务');
    
    const success = schedulerService.stopTask();
    
    if (success) {
      res.json({
        success: true,
        message: '所有定时任务停止成功',
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(500).json({
        success: false,
        error: '停止定时任务失败',
        message: '部分或全部定时任务停止失败',
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error('停止所有定时任务失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '停止定时任务失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

/**
 * @route POST /api/scheduler/restart
 * @desc 重启定时任务调度器
 * @access Private
 */
router.post('/restart', async (req, res) => {
  try {
    logger.info('重启定时任务调度器');
    
    const success = await schedulerService.restart();
    
    if (success) {
      res.json({
        success: true,
        message: '定时任务调度器重启成功',
        timestamp: new Date().toISOString()
      });
    } else {
      res.status(500).json({
        success: false,
        error: '重启定时任务调度器失败',
        message: '重启过程中出现错误',
        timestamp: new Date().toISOString()
      });
    }
  } catch (error) {
    logger.error('重启定时任务调度器失败', { error: error.message });
    res.status(500).json({
      success: false,
      error: '重启定时任务调度器失败',
      message: error.message,
      timestamp: new Date().toISOString()
    });
  }
});

module.exports = router;
